import {
  mkdir,
  appendFile,
  readFile,
  writeFile,
  copyFile,
  access,
} from "fs/promises";
import { constants } from "fs";
import { join } from "path";
import chalk from "chalk";
import requireJson from "./requireJson.cjs";
import { cwd } from "process";
const vueTempGenerate = async (vuePath) => {
  const data = `
<template>
    <div></div>
</template>
<script setup lang="ts"></script>
<style lang="less"></style>
`;
  //如果文件不存在再进行写入
  access(vuePath, constants.F_OK).catch((err) => {
    appendFile(vuePath, data);
  });
};
const mkdirByRoutePath = async (routeConfigArr, projectDir) => {
  //获取路由中使用的antDesign的icon
  let iconArr = [];
  for (let item of routeConfigArr.values()) {
    if (item["component"]) {
      //只能创建文件夹
      let compPath = item["component"].split("/");
      let compFile = `${compPath[compPath.length - 1]}.vue`;
      compPath.splice(compPath.length - 1, 1);
      let compPathStr = compPath.join("/");
      let componentPath = join(projectDir, "src/views", compPathStr);
      await mkdir(componentPath, {
        recursive: true,
      }).catch(() => {
        console.log(`${chalk.red("mkdir error")}`);
      });
      vueTempGenerate(join(componentPath, compFile));
    } else {
      if (item["children"]) {
        let tempIconArr = await mkdirByRoutePath(item["children"], projectDir);
        iconArr = [...iconArr, ...tempIconArr];
      }
    }
    if (item["meta"] && item["meta"]["icon"]) {
      iconArr.push(item["meta"]["icon"]);
    }
  }
  return iconArr;
};

const changeSideBarIcon = async (projectDir, iconArr) => {
  let iconStr = iconArr.join();
  let tplStr = `import { ${iconStr} } from '@ant-design/icons-vue';`;
  let tplIconData = `const iconData = { ${iconStr} };`;
  let fileName = join(projectDir, "src/components/layouts/Sidebar.vue");
  // console.log(fileName, "fileName");
  readFile(fileName, { encoding: "utf-8" })
    .then((res) => {
      let tmpFileStr = res.replace("///{{{import}}}", tplStr);
      tmpFileStr = tmpFileStr.replace("///{{{iconData}}}", tplIconData);
      writeFile(fileName, tmpFileStr);
    })
    .catch(() => {
      console.log(`${chalk.red("create fail")}`);
    });
};

const init = async (projectDir, options) => {
  if (!options?.config) {
    return true;
  }
  let routeConfigJson = requireJson(join(cwd(), options.config));
  mkdirByRoutePath(routeConfigJson["default"]["route"], projectDir);
  const iconArr = await mkdirByRoutePath(
    routeConfigJson["default"]["menu"],
    projectDir
  );
  changeSideBarIcon(projectDir, iconArr);
  copyFile(`${options.config}`, join(projectDir, "src/api", "menuData.ts"));
};

const modifyPackageJson = async (projectDir, answers) => {
  let fileName = join(projectDir, "package.json");
  let packageJsonStr = await readFile(fileName, {
    encoding: "utf8",
  });
  packageJsonStr = packageJsonStr.replace("///{{{name}}}", answers.name);
  packageJsonStr = packageJsonStr.replace("///{{{version}}}", answers.version);
  packageJsonStr = packageJsonStr.replace("///{{{author}}}", answers.author);
  writeFile(fileName, packageJsonStr).catch(() => {
    console.log(`${chalk.red("modifyPackage fail")}`);
  });
};

export { init, modifyPackageJson };
